import { type ClassValue, clsx } from "clsx"
import { twMerge } from "tailwind-merge"

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs))
}

export function formatDate(date: Date): string {
  return new Intl.DateTimeFormat('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
  }).format(date)
}

export function formatDateTime(date: Date): string {
  return new Intl.DateTimeFormat('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  }).format(date)
}

export function getGradeName(gradeLevel: number): string {
  if (gradeLevel >= 1 && gradeLevel <= 5) {
    return `小学${gradeLevel}年级`
  } else if (gradeLevel >= 6 && gradeLevel <= 9) {
    return `初中${gradeLevel - 5}年级`
  }
  return '未知年级'
}

export function getDifficultyName(difficulty: number): string {
  const names = ['', '基础', '简单', '中等', '困难', '竞赛']
  return names[difficulty] || '未知'
}

export function getDifficultyColor(difficulty: number): string {
  const colors = [
    '',
    'text-green-600 bg-green-100',
    'text-blue-600 bg-blue-100',
    'text-yellow-600 bg-yellow-100',
    'text-orange-600 bg-orange-100',
    'text-red-600 bg-red-100'
  ]
  return colors[difficulty] || 'text-gray-600 bg-gray-100'
}

export function shuffleArray<T>(array: T[]): T[] {
  const shuffled = [...array]
  for (let i = shuffled.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]]
  }
  return shuffled
}

export function getRandomItems<T>(array: T[], count: number): T[] {
  const shuffled = shuffleArray(array)
  return shuffled.slice(0, count)
}

export function calculateAccuracy(correct: number, total: number): number {
  if (total === 0) return 0
  return Math.round((correct / total) * 100)
}

export function formatPercentage(value: number): string {
  return `${value}%`
}

export function debounce<T extends (...args: any[]) => any>(
  func: T,
  wait: number
): (...args: Parameters<T>) => void {
  let timeout: NodeJS.Timeout | null = null
  
  return (...args: Parameters<T>) => {
    if (timeout) {
      clearTimeout(timeout)
    }
    
    timeout = setTimeout(() => {
      func(...args)
    }, wait)
  }
}

export function throttle<T extends (...args: any[]) => any>(
  func: T,
  limit: number
): (...args: Parameters<T>) => void {
  let inThrottle: boolean
  
  return (...args: Parameters<T>) => {
    if (!inThrottle) {
      func(...args)
      inThrottle = true
      setTimeout(() => inThrottle = false, limit)
    }
  }
}
